// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
  env: process.env.Env
})
const dateUtils = require('date-utils')
const db = cloud.database()
const _ = db.command

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  switch(event.action) {
    case 'saveUser': {      
      return saveUser(event)
    }
    case 'updateUser': {
      return updateUser(event)
    }
    case 'updateAuthorOpenId': {
      return updateAuthorOpenId(event)
    }
    default:
      break
  }
}

async function saveUser(event) {
  try {
    let collection = 'mini_users'
    let user = event.user
    await db.collection(collection).add({
      data: user
    })
    return true;
  } catch (e) {
    addLog('error', 'saveUser', e)
    return false;
  }
}

async function updateUser(event) {
  try {
    let collection = 'mini_users'
    let user = event.user
    let id = user._id
    delete user._id
    delete user.createTime
    await db.collection(collection).doc(id).update({
      data: user
    })
    return true;
  } catch (e) {
    addLog('error', 'updateUser', e)
    return false;
  }
}

async function updateAuthorOpenId(event) {
  let openId = event.userInfo.openId;
  addLog('info', 'updateAuthorOpenId', '1 update author:' + event.authorId + ', openId:' + openId)
  await db.collection('mini_authors').doc(event.authorId)
  .update({
    data: {
      openId: openId,
      avatar: event.avatar
    }
  })
  .then(res=>{
    addLog('info', 'updateAuthorOpenId', '2 update author:'+event.authorId+', openId:'+openId)
  })
  .catch(e => {
    addLog('error', 'updateAuthorOpenId', e)
  })
  return true
}

async function addLog(level, action, msg) {
  try {
    let data = {
      level: level,
      action: action,
      msg: msg,
      timestamp: new Date(Date.now() + (8 * 60 * 60 * 1000)).toFormat("YYYY-MM-DD HH24:MI:SS"),
    }
    return await db.collection('mini_logs').add({
      data: data
    }).then(res => {
      return true
    }).catch(error => {
      console.error(e);
      return false
    })
  } catch (e) {
    console.error(e);
  }
  return false
}